package com.jie.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jie.reggie.commen.R;
import com.jie.reggie.dto.DishDto;
import com.jie.reggie.entity.Dish;
import com.jie.reggie.entity.DishFlavor;
import com.jie.reggie.mapper.DishMapper;
import com.jie.reggie.service.DishFlavorService;
import com.jie.reggie.service.DishService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 曾豪杰
 * @Date: 2022/09/02/15:12
 * @Description:
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    /**
    * @Description: 新增菜品，同时操作2张表
    * @Param: [dishDto]
    * @return: void
    * @Author: 曾豪杰
    * @Date: 2022/9/2
    */
    @Override
    @Transactional//事务统一
    public void saveWithFlavor(DishDto dishDto) {
        //菜品基本信息到dish
        this.save(dishDto);
        //菜品id
        Long id = dishDto.getId();
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors=flavors.stream().map((item)->{
            item.setDishId(id);
            return  item;
                }
        ).collect(Collectors.toList());
        //保存菜品口味到口味表
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //获取菜品
        Dish byId = this.getById(id);

        DishDto dishDto=new DishDto();
        //拷贝
        BeanUtils.copyProperties(byId,dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        //查询口味表
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    /**
    * @Description: 更新
    * @Param: [dishDto]
    * @return: void
    * @Author: 曾豪杰
    * @Date: 2022/9/3
    */
    public void updateWithFlavor(DishDto dishDto) {
        //修改菜品基本信息
        this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        //删除口味
        dishFlavorService.remove(queryWrapper);
        //重新设置
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        //批量添加
        dishFlavorService.saveBatch(flavors);
    }

}
